package com.etmvc.controller.test;

import java.io.File;
import java.util.Date;

import com.et.mvc.JspView;
import com.et.mvc.MultipartFile;
import com.et.mvc.View;
import com.etmvc.core.AuthName;
import com.etmvc.core.ManageController;
import com.etmvc.model.test.User;
import com.etmvc.service.test.UserService;
@AuthName("demo-用户管理")
public class UserController extends ManageController{
	
	private UserService userService = new UserService();
	@AuthName(value="用户列表页",menu=true)
	public void index(){
		request.setAttribute("users", userService.findAll());
	}
	@AuthName("添加用户")
	public View add(User user,MultipartFile file1,MultipartFile file2) throws Exception{
		//测试校验
		user.validate();
        if (user.getErrors().size() != 0) {
        	//校验未通过
        	request.setAttribute("user", user);
        	index();
        	//直接调forward
//        	forward("/views/test/user/index.jsp");
//        	return null;
        	//返回全路径，指向任意文件
//        	return new JspView("/views/test/user/index.jsp");
        	//返回相对路径
        	return new JspView("index");
		}
        //测试文件上传
		if (file1 != null && file1.getSize()!=0) {
			file1.transferTo(new File(super.getServletContext().getRealPath("/")+ "uploads/" + file1.getOriginalFilename()));
			user.setPic("uploads/"+file1.getOriginalFilename());
		}
		if (file2 != null && file2.getSize()!=0) {
			file2.transferTo(new File(super.getServletContext().getRealPath("/")+ "uploads/" + file2.getOriginalFilename()));
			user.setHeadpic("uploads/"+file2.getOriginalFilename());
		}
		user.setCreatetime(new Date());
		userService.add(user);
		try {
			//重定向
			redirect("index");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	@AuthName("删除用户")
	public void delete(int id){
		userService.delete(id);
		try {
			redirect("index");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void modify(int id){
		User user = userService.findById(id);
		if (user == null) {
			request.setAttribute("err", "该用户不存在");
		}else {
			request.setAttribute("user",user);
		}
	}
	
	public void update(int id,String name,int age){
		userService.update(id,name,age);
		try {
			redirect("index");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
